package com.wm.blog_admin.event;

import com.wm.blog_admin.domain.MailDo;
import com.wm.blog_admin.service.SendEmailService;
import com.wm.blog_common.util.StringUtil;
import com.wm.blog_config.config.MailProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.mail.MessagingException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author 半卷流年  监听邮件事件变化
 * @date 2020-4-29 11:23
 */
@Component
@Slf4j
public class MailEventListener implements ApplicationListener<MailEvent> {

    @Autowired
    private SendEmailService sendEmailService;

    @Autowired
    private MailProperties mailProperties;

    @Override
    public void onApplicationEvent(MailEvent event) {
        MailDo mailDo = Optional.ofNullable(event.getMailDo()).orElse(MailDo.builder().build());
        if(StringUtil.isEmpty(mailDo.getFrom()) || CollectionUtils.isEmpty(mailDo.getToList())){
            log.info("发件人/收件人为空....");
            return;
        }
        String from = mailProperties.getUsername();
        String subject = mailDo.getSubject();
       List<String> toList = Optional.ofNullable(mailDo.getToList()).orElse(Collections.emptyList());
       log.info("邮件发送人:[{}],邮件接收人:[{}]",from,toList);
        if(mailDo.getFlag()){
            //发送html模板邮件
            String htmlName = mailDo.getHtmlName();
            Map<String,Object> paraMap = Optional.ofNullable(mailDo.getParamsMap()).orElse(Collections.emptyMap());
            try {
                sendEmailService.sendHtmlMail(toList,from,subject,htmlName,paraMap);
            } catch (MessagingException e) {
               log.error("发送邮件到[{}]失败",toList,e);
            }
        }else{
            //发送普通邮件
            String content = mailDo.getContent();
            sendEmailService.sendSimpleMail(toList,from,subject,content);
        }
    }
}
